﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.Products.Repositories;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.Products.Services
{
    public class ProductManager : DomainService
    {
        private IProductRepository _repository;
        private IGuidGenerator _guidGenerator;
        private IProductInventoryRepository _inventoryRepository;

        public ProductManager(IProductRepository repository, IGuidGenerator guidGenerator, IProductInventoryRepository inventoryRepository)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
            _inventoryRepository = inventoryRepository;
        }

        public async Task<Product> GetAsync(Guid? id, string code, string name, ProductType type, string barcode, Guid basicUnitId, Guid? defaultTaxRateId, Guid? defaultSupplierId, string model, bool activated)
        {
            var matchCount = (await _repository.GetCountAsync(code, null, id)) + (await _repository.GetCountAsync(null, code, id));

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            Product product;

            if (id.HasValue)
            {
                product = await _repository.GetAsync(id.Value);

                if (product == null)
                    throw new UserFriendlyException($"产品：{id}不存在", "100000");

                await ValidateBaiscUnitAsync(product, basicUnitId);

                product.Change(code, name, type, barcode, basicUnitId, defaultTaxRateId, defaultSupplierId, model, activated);
            }
            else
                product = new Product(_guidGenerator.Create(), code, name, type, barcode, basicUnitId, defaultTaxRateId, defaultSupplierId, model, activated);

            return product;
        }

        private async Task ValidateBaiscUnitAsync(Product product, Guid basicUnitId)
        {
            if (product.BasicUnitId == basicUnitId)
                return;

            var inventoryCount = await _inventoryRepository.GetCountAsync(product.Id);

            if (inventoryCount > 0)
                throw new UserFriendlyException("产品存在库存数据,不允许更改计价单位");
        }
    }
}
